using System.Collections.Generic;
using LitJson;
using UnityEngine;
using UnityEngine.UI;
namespace CGF
{
    public partial class PanelWithdraw : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        //不同国家支持的收款方式
        public static Dictionary<EArea, string[]> CanUseMethods = new Dictionary<EArea, string[]>()
        {
            { EArea.Common, new[] { "bank" } },
            { EArea.China, new[] { "bank" } },
            { EArea.Brazil, new[] { "pix" } },
            { EArea.India, new[] { "bank" } },
            { EArea.Vietnam, new[] { "bank" } },
        };
        private List<JsonData> myMethods = new List<JsonData>();
        private int currSelectIndex;
        private CButton[] dropdownCellPrefabs;

        public static void Open()
        {
            UIManagerComponent.instance.OpenUI<PanelWithdraw>(UILayer.Normal, RootComponent.instance, false);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelWithdraw>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelWithdraw", layer, isFloat);
            BindProperties(transform);

            BtnBack.SetClick(Close);
            BtnAddWay.SetClick(() => { PanelWithdrawAdd.Open(); });

            BtnCurrWayEdit.SetClick(() =>
            {
                //Dialog.Alert(I18N_please_contact_service);
                Sprite iconSprite = BtnCurrWay.gameObject.Get<Image>("Icon").sprite;
                PanelWithdrawEdit.Open(iconSprite, myMethods[currSelectIndex]);
            });

            Ways.gameObject.SetActive(false);
            InputAmount.gameObject.SetActive(false);
            InputPasswd.gameObject.SetActive(false);
            BtnSetPasswd.gameObject.SetActive(false);
            BtnAddWay.gameObject.SetActive(false);

            Dropdown.rectTransform.anchoredPosition = new Vector2(-100, Dropdown.rectTransform.anchoredPosition.y);

            dropdownCellPrefabs = new CButton[Dropdown.cells.Length];
            for (int i = 0; i < dropdownCellPrefabs.Length; i++)
            {
                dropdownCellPrefabs[i] = Dropdown.cells[i];
                dropdownCellPrefabs[i].gameObject.SetActive(false);
            }
            Dropdown.ResetCells(new CButton[0]);

            BtnSetPasswd.SetClick(() =>
            {
                PanelEditPassword.Open(PanelEditPassword.Type.WithdrawPasswd);
            });

            Dropdown.SetOnSelect(index =>
            {
                var cell = Dropdown.cells[index];
                var image = BtnCurrWay.gameObject.Get<Image>("Icon");
                image.sprite = cell.gameObject.Get<Image>("Icon").sprite;
                image.SetNativeSize();
                string method = cell.gameObject.Get<Text>("Text").text;
                BtnCurrWay.gameObject.Get<Text>("Name").text = method;
                currSelectIndex = index;
            });

            BtnCurrWay.SetClick(() =>
            {
                Dropdown.Show();
            });

            BtnSubmit.SetClick(async () =>
            {
                if (string.IsNullOrEmpty(InputAmount.text))
                {
                    Dialog.Alert(I18N_please_input_amount);
                    return;
                }
                if (float.Parse(InputAmount.text) < Config.Get.WithdrawMin)
                {
                    Dialog.Alert(CommAssets.instance.I18N_withdraw_min_tip.Replace("{num}", Config.Get.WithdrawMin.ToString()));
                    return;
                }
                if (InputAmount.text.Contains("."))
                {
                    Dialog.Alert(I18N_amount_must_be_int);
                    return;
                }
                int amount = int.Parse(InputAmount.text) * 100;
                if (amount <= 0)
                {
                    Dialog.Alert(I18N_invalid_amount);
                    return;
                }
                if (amount > UserInfo.balance)
                {
                    Dialog.Alert(I18N_balance_not_enough);
                    return;
                }
                if (string.IsNullOrEmpty(InputPasswd.text))
                {
                    Dialog.Alert(I18N_please_input_passwd);
                    return;
                }
                if (!StringHelper.IsNumberAndLetter(InputPasswd.text))
                {
                    Dialog.Alert(CommAssets.instance.I18N_passwd_must_letter8);
                    return;
                }
                JsonData data = new JsonData();
                data["amount"] = amount;
                data["method_id"] = myMethods[currSelectIndex]["id"];
                data["password"] = InputPasswd.text;
                Dictionary<string, Network.CustomPopupMsgs> customPopupMsgs = new Dictionary<string, Network.CustomPopupMsgs>()
                {
                    {
                        "Invalid password", new Network.CustomPopupMsgs()
                        {
                            msg = $"{I18N_wrong_passwd}\n{I18N_set_passwd_first}", onClose = () =>
                            {
                                PanelEditPassword.Open(PanelEditPassword.Type.WithdrawPasswd);
                            }
                        }
                    }
                };
                var res = await Network.Post("/v1/withdrawal", data, customPopupMsgs: customPopupMsgs);
                if (res.success)
                {
                    Close();
                    PopupSucWithdraw.Open();
                }
            });

            TextServiceTip.text = $"<color=#888888>{I18N_service_fee.Replace("{num}", Config.WithdrawFeePercent + "%")}</color>";
            TextServiceTip.text += $"\n{I18N_xianshi_tehui.Replace("{num}", Config.WithdrawFeePercentDiscount + "%")}";
            
            BottomTip.text = I18N_bottom_tip.Replace("{num}", $"{I18N.Currency}{Config.Get.WithdrawMin}");

            EventManager.Add<Event_UserInfoUpdate>(OnUserInfoUpdate);

            ReqData();
        }

        public async void ReqData()
        {
            //钱包数据
            WalletDetail.text = $"{I18N_can_withdraw}: {I18N.Currency} {StringHelper.Format2Decimal(UserInfo.balance * 0.01f)}";
            WalletDetail.text += "      ";
            WalletDetail.text += $"{I18N_can_not_withdraw}: {I18N.Currency} {StringHelper.Format2Decimal(UserInfo.remain * 0.01f)}";

            //支付列表
            //{"code":200,"message":"Successfully return","data":[{"id":361247579977027584,"user_id":352503699425202176,"method":"PIX","account":"abc"}]}
            var res = await Network.Get("/v1/withdrawal/way");
            myMethods.Clear();
            JsonData _methods = res.jsonData["data"];
            for (int i = 0; i < _methods.Count; i++)
            {
                myMethods.Add(_methods[i]);
            }
            if (myMethods.Count > 0)
            {
                ShowWays();
            }
            for (int i = 0; i < Dropdown.cells.Length; i++)
            {
                GameObject.Destroy(Dropdown.cells[i].gameObject);
            }
            List<CButton> myCells = new List<CButton>();
            for (int i = 0; i < myMethods.Count; i++)
            {
                string method = myMethods[i]["method"].ToString();
                CButton prefab = null;
                if (method.Contains("pix"))
                {
                    prefab = dropdownCellPrefabs[0];
                }
                else if (method.Contains("usdt"))
                {
                    prefab = dropdownCellPrefabs[1];
                }
                else if (method.Contains("bank"))
                {
                    prefab = dropdownCellPrefabs[2];
                }
                if (prefab)
                {
                    CButton cell = GameObject.Instantiate(prefab, Dropdown.transform, false);
                    cell.gameObject.SetActive(true);
                    myCells.Add(cell);
                }
            }
            Dropdown.ResetCells(myCells.ToArray());
            if (myCells.Count > 0)
            {
                Dropdown.InvokeSelect(0);
            }

            BtnAddWay.gameObject.SetActive(myCells.Count < CanUseMethods[CGFConfig.Instance.ReleaseArea].Length);
        }

        public void ShowWays()
        {
            Ways.gameObject.SetActive(true);
            InputAmount.gameObject.SetActive(true);
            bool haveSetPw = !string.IsNullOrEmpty(UserInfo.Info["withdrawal_password"].ToString());
            InputPasswd.gameObject.SetActive(haveSetPw);
            BtnSetPasswd.gameObject.SetActive(!haveSetPw);
        }

        private void OnUserInfoUpdate(Event_UserInfoUpdate e)
        {
            ShowWays();
        }

        public void RefreshMethodData(JsonData data)
        {
            for (int i = 0; i < myMethods.Count; i++)
            {
                if (myMethods[i]["id"].ToString() == data["id"].ToString())
                {
                    myMethods[i] = data;
                    break;
                }
            }
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            EventManager.Remove<Event_UserInfoUpdate>(OnUserInfoUpdate);
        }

    }
}
